import { Component, OnInit ,ViewChild } from '@angular/core';
import { GetMusicService } from '../../../providers/getMusic';
import { Music,Filelist } from '../../../providers/global';
import { NZ_MESSAGE_CONFIG } from 'ng-zorro-antd';
import {NzMessageService} from 'ng-zorro-antd';
@Component({
  selector: 'app-add-music',
  templateUrl: './add-music.component.html',
  styleUrls: ['./add-music.component.css'],
  providers:[{ provide: NZ_MESSAGE_CONFIG, useValue: { nzDuration: 3000 } }]
})
export class AddMusicComponent implements OnInit {
  @ViewChild('nzTable') table;
  isSearch: boolean = false;
  isSelected: boolean = false;
  deleteId: string;
  musicInfos: Music[] = [];
  sname: any;
  isLoading = false;
  isLoading2 = false;
  results:any[]
  constructor( public getMusic: GetMusicService,private message: NzMessageService) {
    
   }

  ngOnInit() {
    this.getMusic.searchFresh().subscribe();
  }
  delete() {
    this.getMusic.delete(this.deleteId).subscribe();
  }
  filterName(query, filelist: any[]):any[] {
    let filtered : any[] = [];
    for(let i = 0; i < filelist.length; i++) {
        let file = filelist[i];
        if(file.name.toLowerCase().indexOf(query.toLowerCase()) == 0) {
            filtered.push(file);
        }
    }
    return filtered;
}
  searchRes=(event)=>{
    let query = event.query;
    this.getMusic.searchRes().then(filelist => {
      this.results = this.filterName(query, filelist);
   })
  }

  select= (e) =>{
    this.isSelected = true;
  }
  loading=()=> {
    this.musicInfos = [];
    this.isLoading = true;
    let data =  this.isSelected?this.sname.name:this.sname;
    this.getMusic.search(data).subscribe(data => {
      let res = data.json().data.song.list;
      for (var i = 0; i < res.length; i++) {
        let str = res[i].f.split("|");
        this.musicInfos.push(
            {
              album:str[5],
              id:str[20],
              name:res[i].fsong,
              singer:this.judge(res[i]),
          }
        );
      }
      this.isSearch = true;
      this.sname = "";
      this.isSelected = false;
      this.isLoading = false;
      this.isLoading2 = false;
    }
    );

  };

  ok =(value,name)=> {
    this.isLoading2 = true;
    this.getMusic.add(value).subscribe(() => {
      this.message.create('success', `成功添加${name}`);
      this.isLoading2 = false;
    }, error => {
      console.log(error);
    }

    );
  }

  judge(data) {

    return data.fsinger2 ? data.fsinger + "/" + data.fsinger : data.fsinger;

  }
}
